<template>
  <div class="import-button">
    <el-upload
      ref="uploadRef"
      :auto-upload="false"
      :show-file-list="false"
      :accept="acceptedFormats"
      :before-upload="handleBeforeUpload"
      @change="handleFileChange"
    >
      <el-button type="success" :loading="importing">
        <el-icon><Upload /></el-icon>
        导入数据
      </el-button>
    </el-upload>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="数据导入"
      width="1200px"
      :close-on-click-modal="false"
    >
      <div v-if="importStep === 1" class="import-step">
        <h3>步骤1：选择文件</h3>
        <el-upload
          ref="fileUploadRef"
          :auto-upload="false"
          :show-file-list="true"
          :accept="acceptedFormats"
          :before-upload="handleBeforeUpload"
          @change="handleFileSelect"
        >
          <el-button type="primary">
            <el-icon><Upload /></el-icon>
            选择文件
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持 CSV、JSON 格式文件，文件大小不超过 10MB
            </div>
          </template>
        </el-upload>
      </div>

      <div v-if="importStep === 2" class="import-step">
        <h3>步骤2：字段映射</h3>
        <div class="mapping-container">
          <div class="mapping-header">
            <span>请将文件中的列映射到系统字段：</span>
            <el-button type="text" @click="autoMapping">自动映射</el-button>
          </div>
          <el-table :data="mappingData" border>
            <el-table-column prop="systemField" label="系统字段" width="200">
              <template #default="{ row }">
                <el-select v-model="row.systemField" placeholder="请选择" style="width: 100%">
                  <el-option 
                    v-for="field in availableFields" 
                    :key="field.value" 
                    :label="field.label" 
                    :value="field.value" 
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="fileField" label="文件字段" width="200">
              <template #default="{ row }">
                <el-select v-model="row.fileField" placeholder="请选择" style="width: 100%">
                  <el-option 
                    v-for="field in fileHeaders" 
                    :key="field" 
                    :label="field" 
                    :value="field" 
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="required" label="必填" width="80">
              <template #default="{ row }">
                <el-tag v-if="row.required" type="danger" size="small">必填</el-tag>
                <el-tag v-else type="info" size="small">可选</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sample" label="示例数据" />
          </el-table>
        </div>
      </div>

      <div v-if="importStep === 3" class="import-step">
        <h3>步骤3：数据预览</h3>
        <div class="preview-container">
          <div class="preview-stats">
            <el-alert
              :title="`共 ${previewData.totalRows} 行数据，有效 ${previewData.validRows} 行，错误 ${previewData.errorRows} 行`"
              :type="previewData.valid ? 'success' : 'warning'"
              show-icon
            />
          </div>
          
          <div v-if="previewData.errors.length > 0" class="error-list">
            <h4>错误信息：</h4>
            <el-table :data="previewData.errors" size="small" max-height="200">
              <el-table-column prop="row" label="行号" width="80" />
              <el-table-column prop="errors" label="错误信息">
                <template #default="{ row }">
                  <div v-for="error in row.errors" :key="error" class="error-item">
                    {{ error }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div v-if="previewData.warnings.length > 0" class="warning-list">
            <h4>警告信息：</h4>
            <el-table :data="previewData.warnings" size="small" max-height="200">
              <el-table-column prop="row" label="行号" width="80" />
              <el-table-column prop="warnings" label="警告信息">
                <template #default="{ row }">
                  <div v-for="warning in row.warnings" :key="warning" class="warning-item">
                    {{ warning }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="preview-table">
            <h4>数据预览（前10行）：</h4>
            <el-table :data="previewData.validData.slice(0, 10)" border size="small">
              <el-table-column 
                v-for="field in mappedFields" 
                :key="field.value" 
                :prop="field.value" 
                :label="field.label" 
                width="150"
              />
            </el-table>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button v-if="importStep > 1" @click="handlePrev">上一步</el-button>
          <el-button 
            v-if="importStep < 3" 
            type="primary" 
            @click="handleNext"
            :disabled="!canProceed"
          >
            下一步
          </el-button>
          <el-button 
            v-if="importStep === 3" 
            type="primary" 
            @click="handleImport"
            :loading="importing"
            :disabled="!previewData.valid"
          >
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseCSV, parseJSON, validateImportData, transformData, getDefaultImportRules, getDefaultFieldMapping } from '@/utils/import'

const props = defineProps({
  // 数据类型
  dataType: {
    type: String,
    required: true
  },
  // 接受的文件格式
  acceptedFormats: {
    type: String,
    default: '.csv,.json'
  },
  // 最大文件大小（MB）
  maxSize: {
    type: Number,
    default: 10
  }
})

const emit = defineEmits(['import', 'import-success', 'import-error'])

// 响应式数据
const importing = ref(false)
const importDialogVisible = ref(false)
const importStep = ref(1)
const uploadRef = ref()
const fileUploadRef = ref()

// 文件相关
const selectedFile = ref(null)
const fileHeaders = ref([])
const fileData = ref([])

// 映射相关
const mappingData = ref([])
const availableFields = ref([])

// 预览相关
const previewData = ref({
  valid: false,
  validData: [],
  errors: [],
  warnings: [],
  totalRows: 0,
  validRows: 0,
  errorRows: 0
})

// 计算属性
const canProceed = computed(() => {
  if (importStep.value === 1) {
    return selectedFile.value !== null
  } else if (importStep.value === 2) {
    return mappingData.value.every(item => item.systemField && item.fileField)
  }
  return true
})

const mappedFields = computed(() => {
  return mappingData.value
    .filter(item => item.systemField && item.fileField)
    .map(item => ({
      value: item.systemField,
      label: item.label
    }))
})

// 方法
const handleBeforeUpload = (file) => {
  const isValidFormat = props.acceptedFormats.split(',').some(format => 
    file.name.toLowerCase().endsWith(format.replace('.', ''))
  )
  
  if (!isValidFormat) {
    ElMessage.error('文件格式不支持')
    return false
  }
  
  const isValidSize = file.size / 1024 / 1024 < props.maxSize
  if (!isValidSize) {
    ElMessage.error(`文件大小不能超过 ${props.maxSize}MB`)
    return false
  }
  
  return true
}

const handleFileChange = (file) => {
  if (file.raw) {
    selectedFile.value = file.raw
    importDialogVisible.value = true
    importStep.value = 1
  }
}

const handleFileSelect = (file) => {
  if (file.raw) {
    selectedFile.value = file.raw
    parseFile(file.raw)
  }
}

const parseFile = async (file) => {
  try {
    importing.value = true
    
    let result
    const fileName = file.name.toLowerCase()
    
    if (fileName.endsWith('.csv')) {
      result = await parseCSV(file)
    } else if (fileName.endsWith('.json')) {
      result = await parseJSON(file)
    } else {
      throw new Error('不支持的文件格式')
    }
    
    fileHeaders.value = result.headers
    fileData.value = result.data
    
    // 初始化字段映射
    initFieldMapping()
    
    importStep.value = 2
    
  } catch (error) {
    ElMessage.error(`文件解析失败：${error.message}`)
  } finally {
    importing.value = false
  }
}

const initFieldMapping = () => {
  const defaultMapping = getDefaultFieldMapping(props.dataType)
  const rules = getDefaultImportRules(props.dataType)
  
  availableFields.value = rules.map(rule => ({
    value: rule.field,
    label: rule.label,
    required: rule.required
  }))
  
  mappingData.value = rules.map(rule => ({
    systemField: '',
    fileField: '',
    label: rule.label,
    required: rule.required,
    sample: fileData.value[0] ? Object.values(fileData.value[0]).join(', ') : ''
  }))
}

const autoMapping = () => {
  const defaultMapping = getDefaultFieldMapping(props.dataType)
  
  mappingData.value.forEach(item => {
    // 尝试自动匹配字段名
    const matchedField = fileHeaders.value.find(header => 
      header.toLowerCase().includes(item.label.toLowerCase()) ||
      item.label.toLowerCase().includes(header.toLowerCase())
    )
    
    if (matchedField) {
      item.fileField = matchedField
    }
  })
}

const handleNext = async () => {
  if (importStep.value === 1) {
    if (selectedFile.value) {
      await parseFile(selectedFile.value)
    }
  } else if (importStep.value === 2) {
    await validateData()
    importStep.value = 3
  }
}

const handlePrev = () => {
  if (importStep.value > 1) {
    importStep.value--
  }
}

const validateData = async () => {
  try {
    importing.value = true
    
    // 转换数据
    const mapping = {}
    mappingData.value.forEach(item => {
      if (item.systemField && item.fileField) {
        mapping[item.systemField] = item.fileField
      }
    })
    
    const transformedData = transformData(fileData.value, mapping)
    
    // 验证数据
    const rules = getDefaultImportRules(props.dataType)
    const result = validateImportData(transformedData, rules)
    
    previewData.value = result
    
  } catch (error) {
    ElMessage.error(`数据验证失败：${error.message}`)
  } finally {
    importing.value = false
  }
}

const handleImport = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要导入 ${previewData.value.validRows} 条数据吗？`,
      '确认导入',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    importing.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success(`成功导入 ${previewData.value.validRows} 条数据`)
    
    emit('import-success', {
      totalRows: previewData.value.totalRows,
      validRows: previewData.value.validRows,
      errorRows: previewData.value.errorRows,
      data: previewData.value.validData
    })
    
    handleCancel()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`导入失败：${error.message}`)
      emit('import-error', error)
    }
  } finally {
    importing.value = false
  }
}

const handleCancel = () => {
  importDialogVisible.value = false
  importStep.value = 1
  selectedFile.value = null
  fileHeaders.value = []
  fileData.value = []
  mappingData.value = []
  previewData.value = {
    valid: false,
    validData: [],
    errors: [],
    warnings: [],
    totalRows: 0,
    validRows: 0,
    errorRows: 0
  }
}
</script>

<style scoped>
.import-button {
  display: inline-block;
}

.import-step {
  min-height: 400px;
}

.import-step h3 {
  margin-bottom: 20px;
  color: #303133;
}

.mapping-container {
  margin-top: 20px;
}

.mapping-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.preview-container {
  margin-top: 20px;
}

.preview-stats {
  margin-bottom: 20px;
}

.error-list,
.warning-list {
  margin-bottom: 20px;
}

.error-list h4,
.warning-list h4 {
  margin-bottom: 10px;
  color: #f56c6c;
}

.warning-list h4 {
  color: #e6a23c;
}

.error-item,
.warning-item {
  margin-bottom: 5px;
  font-size: 12px;
}

.preview-table h4 {
  margin-bottom: 10px;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}
</style>
